package org.ucas.kgraph.service;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.ucas.kgraph.dao.DocumentDao;
import org.ucas.kgraph.dao.RelationDao;
import org.ucas.kgraph.dao.TermDao;
import org.ucas.kgraph.dto.GraphDto;
import org.ucas.kgraph.dto.ListDto;
import org.ucas.kgraph.dto.TermGraphDto;
import org.ucas.kgraph.entity.DocFile;
import org.ucas.kgraph.entity.Document;
import org.ucas.kgraph.entity.Relation;
import org.ucas.kgraph.entity.RelationType;
import org.ucas.kgraph.entity.Term;
import org.ucas.kgraph.entity.TermGraph;
import org.ucas.kgraph.utils.exception.BadRequestException;
import org.ucas.kgraph.utils.exception.ConflictException;
import org.ucas.kgraph.utils.exception.ForbiddenException;
import org.ucas.kgraph.utils.exception.NotFoundException;

import com.fasterxml.jackson.core.JsonParseException;
import com.fasterxml.jackson.databind.DeserializationFeature;
import com.fasterxml.jackson.databind.JsonMappingException;
import com.fasterxml.jackson.databind.ObjectMapper;

import java.io.IOException;
import java.util.*;
import java.util.stream.Collectors;

@Transactional
@Service
public class DocumentService {

  @Autowired
  private DocumentDao documentDao;

  public Document create(Document t){
	  return documentDao.save(t);
  }

  public Document recontent(Long id, String content) {
	// TODO Auto-generated method stub
	Document doc = load(id);
	if(doc == null) throw NotFoundException.Term_NotExists;
	doc.setContent(content);
	return documentDao.save(doc);
  }
  
  public Document load(Long id) {
	    return documentDao.findOne(id);
  }

  public void addDocFile(Long id, DocFile docFile) {
	// TODO Auto-generated method stub
	  Document document = load(id);
	  document.getDocList().add(docFile);
	  documentDao.save(document);
  }

  public Document recontent(Long id, Document fromtmp) {
	Document doc = load(id);
	if(doc == null) throw NotFoundException.Term_NotExists;
	doc.setContent(fromtmp.getContent());
	List<DocFile> docs = new ArrayList<>();
	for(DocFile df:fromtmp.getDocList()){
		docs.add(df);
	}
	
	doc.setDocList(docs);
	return documentDao.save(doc);
  }

  public void deleteDocfile(Long documentId, Long docId) {
	// TODO Auto-generated method stub
	Document doc = load(documentId);
	if(doc == null) throw NotFoundException.Term_NotExists;
	List<DocFile> docFiles = doc.getDocList();
	
	for(int i=0;i<docFiles.size();i++){
		DocFile docFile = docFiles.get(i);
		if(docFile.getId().equals(Long.valueOf(docId))){
			docFiles.remove(docFile);
		}
	}
	documentDao.save(doc);
  }
}
